package com.jason.lightreader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jason.lightreader.entity.Article;
import com.jason.lightreader.entity.CollectionRecord;
import com.jason.lightreader.entity.User;
import com.jason.lightreader.mapper.ArticleMapper;
import com.jason.lightreader.mapper.CollectionRecordMapper;
import com.jason.lightreader.mapper.ScoreMapper;
import com.jason.lightreader.response.Code;
import com.jason.lightreader.response.Result;
import com.jason.lightreader.service.ArticleService;
import com.jason.lightreader.util.SecurityContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@EqualsAndHashCode(callSuper = true)
@Service
@ConfigurationProperties("article-path")
@Data
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CollectionRecordMapper collectionRecordMapper;

    @Autowired
    private ScoreMapper scoreMapper;

    private String url;

    @Override
    public Result getMyCollection() {
        User user = SecurityContext.getUser();
        List<Article> articles = this.getBaseMapper().getArticlesByUserId(user.getId());
        return Result.get(Code.SUCCEED, articles, "获取我的收藏夹成功！");
    }

    @Override
    public Result addOrRemoveToMyCollection(Integer articleID) {
        //判断书籍是否存在
        boolean exists = this.getBaseMapper().exists(
                new LambdaQueryWrapper<>(Article.class)
                        .eq(Article::getId, articleID)
        );
        if (!exists) {
            return Result.get(Code.FAILED, "该文章不存在！请检查参数。");
        }
        //判断记录是否存在
        Integer userID = SecurityContext.getUser().getId();
        LambdaQueryWrapper<CollectionRecord> queryWrapper = new LambdaQueryWrapper<>(CollectionRecord.class)
                .eq(CollectionRecord::getUserId, userID)
                .eq(CollectionRecord::getArticleId, articleID);
        if (collectionRecordMapper.exists(queryWrapper)) {
            //如果记录存在则删除这条记录
            collectionRecordMapper.delete(queryWrapper);
            return Result.get(Code.SUCCEED, false, "收藏已取消！");
        }
        //添加记录
        collectionRecordMapper.insert(new CollectionRecord()
                .setArticleId(articleID)
                .setUserId(userID));
        return Result.get(Code.SUCCEED, true, "该文章已成功添加到收藏夹！");
    }

    @Override
    public Result isCollected(Integer articleID) {
        Integer userID = SecurityContext.getUser().getId();
        Article article = this.getBaseMapper().getCollectionArticleByUserId(userID, articleID);
        if (article == null) {
            return Result.get(Code.SUCCEED, false, "文章未收藏！");
        }
        return Result.get(Code.SUCCEED, true, "文章已收藏！");
    }

    @Override
    public Result getArticleDetails(Integer articleID) {
        Article article = getById(articleID);
        if (Objects.isNull(article)) {
            return Result.get(Code.FAILED, "文章不存在！");
        }
        return Result.get(Code.SUCCEED, article, "获取成功！");
    }

    @Override
    public Result getArticlesByPage(Integer index) {
        IPage<Article> page = new Page<>();
        page.setSize(10)
                .setCurrent(index);
        this.page(page);
        return Result.get(Code.SUCCEED, page.getRecords(), "获取第" + index + "页数据成功！");
    }

    @Override
    public Result getPageCount() {
        IPage<Article> page = new Page<>();
        page.setSize(10);
        this.page(page);
        long pages = page.getPages();
        return Result.get(Code.SUCCEED, pages, "文库共有" + pages + "页");
    }

    @Override
    public Result addOneArticle(Article article, MultipartFile file) {
        if (article.getTitle() == null || article.getIntroduce() == null) {
            return Result.get(Code.FAILED, "对于一篇文章来说标题和简介缺一不可。");
        }
        Integer userID = SecurityContext.getUser().getId();
        if (this.save(article.setUserId(userID))) {
            //获取文章的id
            Integer articleId = article.getId();
            try {
                File file1 = new File(url + articleId + ".md");
                file.transferTo(file1);
                return Result.get(Code.SUCCEED, "添加成功！");
            } catch (IOException e) {
                e.printStackTrace();
                return Result.get(Code.FAILED, "添加失败！");
            }
        }
        return Result.get(Code.FAILED, "添加失败！");
    }

    @Override
    public Result getRecommendArticle() {
        List<Integer> articleIDList = scoreMapper.getArticleIdGroupByArticleId();
        List<Article> articles = this.getBaseMapper().selectBatchIds(articleIDList);
        return Result.get(Code.SUCCEED, articles, "获取到" + articles.size() + "条数据！");
    }

    @Override
    public Result searchArticlesByTitle(String title) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Article::getTitle, title);
        List<Article> articles = this.getBaseMapper().selectList(queryWrapper);
        if (articles.size() > 0) {
            return Result.get(Code.SUCCEED, articles, "查询到" + articles.size() + "条数据！");
        }
        return Result.get(Code.FAILED,"查询结果为空！");
    }
}
